<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class WechatService
{
    protected $appId;
    protected $appSecret;
    
    public function __construct()
    {
        $this->appId = config('wechat.app_id');
        $this->appSecret = config('wechat.app_secret');
    }
    
    /**
     * 通过code获取openid和session_key
     *
     * @param string $code
     * @return array
     * @throws \Exception
     */
    public function code2Session($code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        
        $response = Http::get($url, [
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ]);
        
        $data = $response->json();
        
        if (isset($data['errcode']) && $data['errcode'] != 0) {
            Log::error('微信登录失败', $data);
            throw new \Exception('微信登录失败: ' . ($data['errmsg'] ?? '未知错误'));
        }
        
        return $data;
    }
    
    /**
     * 获取微信接口调用凭证
     *
     * @return string
     * @throws \Exception
     */
    public function getAccessToken()
    {
        return Cache::remember('wechat_access_token', 7000, function () {
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            
            $response = Http::get($url, [
                'grant_type' => 'client_credential',
                'appid' => $this->appId,
                'secret' => $this->appSecret
            ]);
            
            $data = $response->json();
            
            if (isset($data['errcode']) && $data['errcode'] != 0) {
                Log::error('获取微信AccessToken失败', $data);
                throw new \Exception('获取AccessToken失败');
            }
            
            return $data['access_token'];
        });
    }
} 